import React, { useState, useEffect, useRef, useContext } from 'react';
import { TextField, Paper, Grid } from '@mui/material';
import RecursiveTreeView from './RecursiveTreeView'; // 从正确的路径导入
import WorkflowContext from 'contexts/WorkflowContext'; // 根据实际路径导入
import Switch from '@mui/material/Switch';
import { findIndexByField } from 'utils/arrayHelpers'; // 根据实际路径导入
// 自定义的 Autocomplete 组件
const CustomAutocomplete = ({ stepIndex, onChange, onBlur, defaultValue }) => {
  // State
  const [inputValue, setInputValue] = useState(''); // 用户输入值
  const [showDropdown, setShowDropdown] = useState(false); // 是否显示下拉列表
  const [treeData, setTreeData] = useState([]); // 新增：本地 state 用于存储 treeData
  // Refs
  const inputRef = useRef(null); // 输入框引用
  const dropdownRef = useRef(null); // 下拉列表引用

  // Context
  const { fetchConfiguredSteps, transformArrayToTree, stepsLength } = useContext(WorkflowContext);
  // 获取配置的步骤列表并转换为树形数据
  useEffect(() => {
    // 重新解析 treeData

    const configuredSteps = fetchConfiguredSteps();
    const newStepIndex = findIndexByField(configuredSteps, 'pUniqueIndex', stepIndex);
    const newTreeData = transformArrayToTree(configuredSteps).slice(0, newStepIndex);
    setTreeData(newTreeData); // 更新本地 state
  }, [stepsLength]); // 监控 stepsLength 的变化

  useEffect(() => {
    if (defaultValue) {
      setInputValue(defaultValue);
    }
  }, [defaultValue]); // 仅在 defaultValue 改变时运行

  // 定义树形数据的根节点
  // console.log('################oldtreeData', originTreeData);
  const rootData = {
    id: 'root',
    name: '',
    children: treeData
  };

  // 显示下拉列表
  const showDropdownList = () => {
    setShowDropdown(true);
  };

  // 隐藏下拉列表
  const hideDropdownList = (e) => {
    if (inputRef.current.contains(e.target) || (dropdownRef.current && dropdownRef.current.contains(e.target))) {
      return;
    }
    setShowDropdown(false);
  };

  // 选择下拉列表选项
  const selectOption = (option, path) => {
    const newPath = `<[[${path}]]>`;
    const newValue = `${inputValue}${newPath}`;

    setInputValue(newValue);
    setShowDropdown(false);

    // 重要：选择下拉列表时，视为输入框失去焦点，触发onBlur事件
    const event = {
      target: {
        value: newValue
      }
    };
    onBlur(event);

    // 如果有外部 onChange，执行它
    if (onChange) {
      onChange({ target: { value: newValue } });
    }
  };

  // 处理输入变化
  const handleInputChange = (e) => {
    const currentValue = e.target.value;
    const cursorPosition = inputRef.current.selectionStart;
    const templatePattern = /<\[\[.*?\]\]>/g;

    let match;
    let shouldRemoveTemplate = false;
    // eslint-disable-next-line no-cond-assign
    while ((match = templatePattern.exec(inputValue)) !== null) {
      console.log('match');
      if (cursorPosition > match.index && cursorPosition <= match.index + match[0].length) {
        shouldRemoveTemplate = true;
        break;
      }
    }

    if (shouldRemoveTemplate) {
      const newValue = inputValue.replace(match[0], '');
      setInputValue(newValue);
    } else {
      setInputValue(currentValue);
    }
    // 如果外部传入了 externalOnChange，则执行它
    if (onChange) {
      onChange(e);
      //
    }
  };

  // 添加和移除事件监听器
  useEffect(() => {
    document.addEventListener('mousedown', hideDropdownList);
    return () => {
      document.removeEventListener('mousedown', hideDropdownList);
    };
  }, []);

  return (
    <Grid container spacing={2}>
      <Grid item xs={12}>
        <TextField
          label="请选择输入"
          variant="outlined"
          value={inputValue}
          onChange={handleInputChange}
          onFocus={showDropdownList}
          onBlur={onBlur}
          inputRef={inputRef}
          fullWidth
          autoComplete="off"
          multiline // 支持多行输入
          rows={2} // 默认显示4行
        />
      </Grid>
      {showDropdown && (
        <Grid item xs={12}>
          <Paper elevation={3} ref={dropdownRef}>
            {/* <Switch onClick={handleInputChange} /> */}
            <RecursiveTreeView options={rootData} selectOption={selectOption} />
          </Paper>
        </Grid>
      )}
    </Grid>
  );
};

export default CustomAutocomplete;
